//
//  WangLuoHomeVC.m
//  Study
//
//  Created by tomato on 2021/8/22.
//  Copyright © 2021 fan. All rights reserved.
//

#import "WangLuoHomeVC.h"
#import "AFNetworking.h"

#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>


@interface WangLuoHomeVC ()<NSURLSessionDownloadDelegate,NSURLSessionDataDelegate>

@property (strong , nonatomic)NSURLSession *session;
@property (strong , nonatomic)NSURLSessionDownloadTask *downloadTask;
@property (strong , nonatomic)NSData *resumeData;

@end

@implementation WangLuoHomeVC


-(NSURLSession *)session{
    
    if (_session == nil) {
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        config.HTTPAdditionalHeaders = @{@"Authorization":@"jhgsbjsuc "};
        
        
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (void)viewDidLoad {
    [super viewDidLoad];

//   [self dataTaskWithHttp];
//    [self download];
//    [self downloadPrecess];
//    [self dunadianxuchuan];
//    [self upload];
    
//    [self httpsUse];
//    [self useAFNetworking_jiben];
    
    [self useSocket];
    
    
}

#pragma mark - Http的使用
/*
 iOS 7.0 以后使用NSURLSession 替代 NSURLConnection 来发送网络请求。
 NSURLSession的特点：
 1、支持后台运行网络任务
 2、暂停、停止、重启网路任务，不需要自己z再封装NSOperation
 3、下载、断点续传、异步下载
 4、获取下载、上传的进度
 5、默认所有的服务都是挂起的
 
 */
#pragma mark - Http的使用
#pragma mark - 获取数据

-(void)dataTaskWithHttp{
    
    //默认是get请求
    NSURL *url = [NSURL URLWithString:@"http://ldu.fanya.chaoxing.com/portal"];//请求地址
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"get";//请求方式
    NSString *body = @"username=123&password=123";//请求体
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    //发起请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
//        id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"请求返回的数据data==%@",data);
        NSLog(@"请求返回的数据response==%@",response);
    }];
    
    //任务默认是挂起的，开启任务
    [dataTask resume];
}


#pragma mark - 下载

-(void)download{
    
    NSURL *url = [NSURL URLWithString:@"http://ldu.fanya.chaoxing.com/portal"];//请求地址
    [[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
        NSLog(@"请求返回的数据location=%@",location);
        NSLog(@"请求返回的数据response=%@",response);
        
        
        //让Session对象无效，去除delegate的强引用，解决循环引用问题，
        //取消操作
        [self.session invalidateAndCancel];//立刻取消
//        [self.session finishTasksAndInvalidate];//下载完成在无效
        
        }] resume];
}
//获取下载进度
-(void)downloadPrecess{
    
    NSURL *url = [NSURL URLWithString:@"https://www.qiaokou.gov.cn/qkxw/tzgg/202108/P020210803401934243317.pdf"];
    [[self.session downloadTaskWithURL:url] resume];

}

#pragma mark - NSURLSessionDownloadDelegate 下载代理
//下载完成
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    
//    NSLog(@"线程=%@",[NSThread currentThread]);
//    NSLog(@"session=%@",session);
//    NSLog(@"downloadTask=%@",downloadTask);
//    NSLog(@"location=%@",location);
}

////获取进度
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    float process = totalBytesWritten*1.0/totalBytesExpectedToWrite;
    NSLog(@"下载进度=%f",process);
//    NSLog(@"线程=%@",[NSThread currentThread]);
//    NSLog(@"bytesWritten=%lld",bytesWritten);
//    NSLog(@"totalBytesWritten=%lld",totalBytesWritten);
//    NSLog(@"totalBytesExpectedToWrite=%lld",totalBytesExpectedToWrite);
}

//续传
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
    
//    NSLog(@"线程=%@",[NSThread currentThread]);
//    NSLog(@"fileOffset=%lld",fileOffset);
//    NSLog(@"expectedTotalBytes=%lld",expectedTotalBytes);
}


#pragma mark - 断点续传
-(void)dunadianxuchuan{
    
    //加载子控件
    [self addKongjian];
}

//开始下载
-(void)kaishiClick{
    
// https://www.qiaokou.gov.cn/qkxw/tzgg/202108/P020210803401934243317.pdf

//  https://gitee.com/xiaochang/PDFWordSelection/repository/blazearchive/master.zip?Expires=1629626798&Signature=7ZPoLEr%2F4p3z2mK8IliVrVBOfYShgB%2BAqNY2rohkKy8%3D
    
    NSURL *url = [NSURL URLWithString:@"https://www.qiaokou.gov.cn/qkxw/tzgg/202108/P020210803401934243317.pdf"];//请求地址
    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithURL:url];
    self.downloadTask = downloadTask;
    [self.downloadTask resume];
}

//暂停下载
-(void)zantingClick{
    
    [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        
        NSLog(@"续传的数据=%@",resumeData);
        self.resumeData = resumeData;
        
        //把续传数据保存到沙盒
        NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"123.tmp"];
        [self.resumeData writeToFile:path atomically:YES];
        NSLog(@"文件路经=%@",path);
        self.downloadTask= nil;
    }];
}

//继续下载
-(void)jixuClick{
    
    //先从沙盒中获取续传数据
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"123.tmp"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        self.resumeData = [NSData dataWithContentsOfFile:path];
    }
    
    
    if (self.resumeData==nil) {
        return;
    }
   //会崩掉
   self.downloadTask =  [self.session downloadTaskWithResumeData:self.resumeData];
   [self.downloadTask resume];
   self.resumeData=nil;
    
}

#pragma mark - 将下载下来的文件解压缩

-(void)yasuoClick{
    
    NSLog(@"压缩");
//https://github.com/Feijunjie/SSZipArchive
}

-(void)jieyaClick{
    
    NSLog(@"解压");
    
}

#pragma mark - 上传文件

-(void)upload{
    
    NSURL *url = [NSURL URLWithString:@"https://www.qiaokou.gov.cn/qkxw/tzgg/202108/P020210803401934243317.pdf"];//请求地址
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"put";//请求方式
    [request setValue:@"" forHTTPHeaderField:@"Authorization"];
    
    //获取上传的文件
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];    //发送网络请求
    [[[NSURLSession sharedSession] uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"返回结果==%@",str);
                
    }] resume];
    
}

//base64编码
-(NSString *)base64Encode:(NSString *)str{
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

#pragma mark - Https的使用

/*
发送请求之前先接收服务器的挑战，就是进行https的协商
 1、信任服务器返回的证书（公钥）
 2、客户端产生随记密钥
 3、公钥对 随机密钥进行加密
 4、把公钥加密后的随机密钥发送给服务器
 5、使用随机密钥对数据加密和服务器交互
 
 */

-(void)httpsUse{
    
    NSURL *url = [NSURL URLWithString:@"https://www.12306.cn/index/"];//请求地址
    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
        NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"请求返回的数据data==%@",html);
            
    }] resume];
}
 
//代理方法
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    
    //判断认证方式，是用户密码，还是证书认证
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        
        //设置信任服务器的证书
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        completionHandler(0,credential);
    }
}

#pragma mark - AFNetworking的使用

-(void)useAFNetworking_jiben{
    
    NSString *url = @"https://www.12306.cn/index/";//请求地址
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    [mgr GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"请求返回的数据downloadProgress==%@",downloadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"请求返回的数据responseObject==%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"请求返回的数据error==%@",error);
        
    }];

}


#pragma mark - Socket的使用

-(void)useSocket{
/*
 1、创建Socket：第一个参数，domin 协议族 制定IPv4
            第二个参数，type Socket类型
              第三个参数，protocol 协议
 */
    int clientSocket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
    
    /*
     2、连接服务器：
     */
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;//协议类型
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");//ip地址
    addr.sin_port = htons(80);//端口
    int result = connect(clientSocket,(const struct sockaddr *)&addr, sizeof(addr));
//    if (result==0) {
//        NSLog(@"成功");
//    }else{
//        NSLog(@"失败");
//    }
    
    if (result !=0) {
        
        NSLog(@"失败");
    }
    
    //3、向服务器发送信息
    const char *mag = "ni hao";
    ssize_t sendCount =  send(clientSocket, mag, strlen(mag), 0);
    NSLog(@"发送的字节数==%zd",sendCount);
    
    
    //4、向服务器发送信息
    uint8_t buffer[1024];
    ssize_t recvCount = recv(clientSocket, buffer, sizeof(buffer), 0);
    NSLog(@"发送的字节数==%zd",recvCount);
    
    //把字符数组转化成字符串
    NSData *data = [NSData dataWithBytes:buffer length:recvCount];
    NSString *recv = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"收到数据==%@",recv);
    //5、关闭连接
    close(clientSocket);
}



#pragma mark - 页面布局

-(void)addKongjian{
    
    UIButton *btn = [[UIButton alloc]init];
    btn.frame =CGRectMake(50,50,50,50);
    btn.backgroundColor = [UIColor blueColor];
    [btn setTitle:@"开始"forState:UIControlStateNormal];
    [btn setTitle:@"开始"forState:UIControlStateHighlighted];//默认白色
    [btn setTitleColor:[UIColor cyanColor]forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor]forState:UIControlStateHighlighted];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(kaishiClick)forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn1 = [[UIButton alloc]init];
    btn1.frame =CGRectMake(50,110,50,50);
    btn1.backgroundColor = [UIColor blueColor];
    [btn1 setTitle:@"暂停"forState:UIControlStateNormal];
    [btn1 setTitle:@"暂停"forState:UIControlStateHighlighted];//默认白色
    [btn1 setTitleColor:[UIColor cyanColor]forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor blueColor]forState:UIControlStateHighlighted];
    [self.view addSubview:btn1];
    [btn1 addTarget:self action:@selector(zantingClick)forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn2 = [[UIButton alloc]init];
    btn2.frame =CGRectMake(50,170,50,50);
    btn2.backgroundColor = [UIColor blueColor];
    [btn2 setTitle:@"继续"forState:UIControlStateNormal];
    [btn2 setTitle:@"继续"forState:UIControlStateHighlighted];//默认白色
    [btn2 setTitleColor:[UIColor cyanColor]forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blueColor]forState:UIControlStateHighlighted];
    [self.view addSubview:btn2];
    [btn2 addTarget:self action:@selector(jixuClick)forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *btn3 = [[UIButton alloc]init];
    btn3.frame =CGRectMake(50,170,50,50);
    btn3.backgroundColor = [UIColor blueColor];
    [btn3 setTitle:@"压缩"forState:UIControlStateNormal];
    [btn3 setTitle:@"压缩"forState:UIControlStateHighlighted];//默认白色
    [btn3 setTitleColor:[UIColor cyanColor]forState:UIControlStateNormal];
    [btn3 setTitleColor:[UIColor blueColor]forState:UIControlStateHighlighted];
    [self.view addSubview:btn3];
    [btn3 addTarget:self action:@selector(yasuoClick)forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn4 = [[UIButton alloc]init];
    btn4.frame =CGRectMake(50,170,50,50);
    btn4.backgroundColor = [UIColor blueColor];
    [btn4 setTitle:@"解压"forState:UIControlStateNormal];
    [btn4 setTitle:@"解压"forState:UIControlStateHighlighted];//默认白色
    [btn4 setTitleColor:[UIColor cyanColor]forState:UIControlStateNormal];
    [btn4 setTitleColor:[UIColor blueColor]forState:UIControlStateHighlighted];
    [self.view addSubview:btn4];
    [btn4 addTarget:self action:@selector(jieyaClick)forControlEvents:UIControlEventTouchUpInside];
    
}

@end
